package com.example.rocketmq.order;

import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;

import java.util.List;

/**
 * 顺序发送消息
 */
public class OrderProducer {
    public static void main(String[] args) throws Exception {
        DefaultMQProducer producer = new DefaultMQProducer("test_group");
        producer.setNamesrvAddr("192.168.228.103:9876");
        producer.start();
        List<Order> orders = Order.orderListMock();
        for (Order order : orders) {
            byte[] body = JSON.toJSONString(order).getBytes();
            Message message = new Message("order_topic", "order", body);
            
            // 参数1：消息对象，参数2：消息队列的选择器，参数3：选择队列的业务标识
            SendResult result = producer.send(message, new MessageQueueSelector() {
                /**
                 *
                 * @param list topic下所有队列的集合
                 * @param message 传入的消息对象回传
                 * @param o 业务标识参数回传
                 */
                @Override
                public MessageQueue select(List<MessageQueue> list, Message message, Object o) {
                    Integer id = (Integer) o;
                    int index = id % list.size();
                    return list.get(index);
                }
            }, order.getOrderId());

            System.out.println(result);
        }
        
        producer.shutdown();
    }
}
